package cn.edu.scau.dormitory_management_system.config;

import cn.edu.scau.dormitory_management_system.entity.PermissionEntity;
import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.service.PermissionService;
import cn.edu.scau.dormitory_management_system.service.impl.PermissionServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.buf.Utf8Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private PermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        UserEntity admin = (UserEntity) request.getAttribute("admin");
        if(admin.getUserId() == 0){
            return true;
        }
        if(url.contains("menu/list")){
            return true;
        }
        List<PermissionEntity> permissionEntities = permissionService.selectPermission(admin.getUserId());
        for (PermissionEntity permissionEntity : permissionEntities) {
            if(permissionEntity.getPerms() == null || permissionEntity.getPerms().equals("")){
                continue;
            }
            String[] split = permissionEntity.getPerms().split(",");
            for (int i = 0; i < split.length; i++) {
                String replace = split[i].replace(":", "/");
                if(url.contains(replace)){
                    return true;
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("code", 403);
        json.put("msg", "权限不足");
        response.setContentType("application/json");
        response.getWriter().write(json.toString());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
